package com.guideir.ota;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HtmlService {
    private static final String TAG = "HtmlService";

    public static String getHtml(String path) throws Exception {
        int val;
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(3 * 1000);
        conn.connect();
        if((val = conn.getResponseCode())==200){
            InputStream inStream = conn.getInputStream();//通过输入流获取html数据
            //得到html的二进制数据
            byte[] data = readInputStream(inStream);
            return new String(data, StandardCharsets.UTF_8);
        } else {
            Log.w(TAG, "HttpURLConnection failed! resp code = " + val);
            return null;
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    private static boolean downloadingOtaPackage(String urlStr, String outputPath, Handler handler) {
        try {
            //get path
            String pathName = Environment.getDataDirectory() + "/" + outputPath;
            Log.w(TAG, "pathName:" + pathName);
            //检查下载文件已经存在
            File file = new File(pathName);
            if(file.exists()) {
                Log.w(TAG, pathName + " already exists!");
                //send msg 3
                Message message3=new Message();
                message3.what=3;
                handler.sendMessage(message3);
                return false;
            }

            /*
             * 通过URL取得HttpURLConnection
             * 要网络连接成功，需在AndroidMainfest.xml中进行权限配置
             * <uses-permission android:name="android.permission.INTERNET" />
             */
            int respCode;
            URL url=new URL(urlStr);
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            //conn.setDoOutput(true);// 使用 URL 连接进行输出
            //conn.setDoInput(true);// 使用 URL 连接进行输入
            //conn.setUseCaches(false);// 忽略缓存
            // 设置URL请求方法
            conn.setRequestMethod("GET");
            //conn.setRequestMethod("POST");
            //conn.setRequestProperty("Content-Type", "application/octet-stream");
            //conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
            //conn.setRequestProperty("Charset", "UTF-8");
            //防止屏蔽程序抓取而返回403错误
            //conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            //设置超时间为3秒
            conn.setConnectTimeout(3 * 1000);
            conn.connect();
            //判断服务端正常的反馈是否已经到达了 客户端
            if ((respCode = conn.getResponseCode()) != HttpURLConnection.HTTP_OK) {
                Log.w(TAG, "download failed! getResponseCode:" + respCode);
                return false;
            }
            //get download file size & send msg 0
            int downloadMaxLen = conn.getContentLength();
            Message message=new Message();
            message.what = 0;
            message.arg1 = downloadMaxLen;
            handler.sendMessage(message);
            //获得网络字节输入流对象
            InputStream input = conn.getInputStream();
            OutputStream output = new FileOutputStream(file);
            int readlen;
            int downloadLen = 0;
            byte[] buffer=new byte[4*1024];
            while ((readlen = input.read(buffer)) != -1) {
                downloadLen += readlen;
                output.write(buffer, 0, readlen);
                //send msg 1
                Message message1=new Message();
                message1.what = 1;
                message1.arg1 = downloadLen;
                handler.sendMessage(message1);
            }
            output.flush();
            output.close();
            if (downloadLen != downloadMaxLen) {
                Log.w(TAG, "download failed! downloadLen != downloadMaxLen");
                return false;
            }
            //设置ACL权限
            String cmd = "chmod 664 " + pathName;
            Log.w(TAG, "run cmd: " + cmd);
            Runtime.getRuntime().exec(cmd);
            //send msg 2
            Message message2=new Message();
            message2.what=2;
            handler.sendMessage(message2);
            Log.w(TAG, "download success");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.w(TAG, "download failed!");
        return false;
    }

    public static void downloadOtaPackage(String urlStr, String outputPath, Handler handler) {
        Thread threadGetHtml = new Thread(() -> {
            try {
                boolean result = downloadingOtaPackage(urlStr, outputPath, handler);
                Log.i(TAG, "result:" + result);
            } catch (Exception e) {
                Log.w(TAG, "downloadOtaPackage failed!");
                e.printStackTrace();
            }
        });
        threadGetHtml.start();
        SystemClock.sleep(500);
    }
}


